package com.test.listener;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class ConfigListern implements ApplicationListener {

	@Autowired
	AbstractApplicationContext ac;
    public void onApplicationEvent(ApplicationEvent event) {
        if (ContextRefreshedEvent.class.getName().equals(event.getClass().getName())) {
            System.out.println("spring 容器启动");
            URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
            try {
            	System.out.println(Arrays.asList(loader.getURLs()));
				Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
//				method.invoke(loader, this.getClass().getResource("BOOT-INF/class/"));
//				method.setAccessible(true);
//				method.invoke(loader, this.getClass().getResource("/BOOT-INF/class/"));
//				ac.refresh();
//				ac.close();
//				ac.refresh();
//				Class<?> main = deduceMainApplicationClass();
//				System.out.println(main.getName());
//				Method method2 = main.getMethod("main",  String[].class);
//				method2.invoke(null, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
            
            
        }else {
        	System.out.println("其他spring容器事件："+event.getClass().getName());
        }
    }
    
    
    private Class<?> deduceMainApplicationClass() {
		try {
			StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
			for (StackTraceElement stackTraceElement : stackTrace) {
				if ("main".equals(stackTraceElement.getMethodName())) {
					return Class.forName(stackTraceElement.getClassName());
				}
			}
		} catch (ClassNotFoundException ex) {
		}
		return null;
	}
}